package simulation;

import java.awt.FlowLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;

/**
 * Authors: Ben Lee
 * Purpose: Calculates and displays the user's score.
 * Version 1
 * Last modified: 11/27/11
 * Tested by:
 * Date tested:
 */

public class ScoreDisplay extends JFrame{
	private Simulation sim;
	
	private double finalScore;
	private int userScore;
	private int simScore;
	
	private JLabel score;
	
	public ScoreDisplay(Simulation s){
		sim = s;
		simScore = s.getSimScore();
		userScore = s.getTotalDelays();
		finalScore = getFinalScore();
		
		score = new JLabel(
			"<html>"
				+"<p>Delay time to beat: " + simScore + "</p>"
				+"<p>Your current delay time: " + userScore + "</p>"
				+"<p>Unscheduled delays are " + getFormattedScore() + "!</p>"
			+"</html>"
		);
		
		this.setLayout(new FlowLayout());
		this.add(score);
		
		this.setBounds(600,100,300,200);
		setDefaultCloseOperation(HIDE_ON_CLOSE);
		this.setVisible(false);
	}

	public int getUserScore() {
		return userScore;
	}

	public void setUserScore(int userScore) {
		this.userScore = userScore;
	}
	
	//Returns the % change from simScore to userScore
	public double getFinalScore(){
		//Avoid division by zero:
		if(simScore == 0)
			return 0; //If there were no delays, they didn't reduce delays.
		else
			return (simScore - userScore) / (float) simScore;
	}
	//Returns the neatly formatted final score that can be put into a label.
	public String getFormattedScore(){
		finalScore = getFinalScore();
		if(finalScore >= 0) //Positive result means userScore < simScore, which means the player was faster.
			//"%1$.0f" means remove the decimal part.  Multiply by 100 to get %.
			return String.format("%1$.0f", finalScore*100) + "% better";
		else //Make it positive, because we're presenting the sign as "improvement" or "worsening".
			return String.format("%1$.0f", Math.abs(finalScore*100)) + "% worse";			
	}
	public void updateScore(){
		userScore = sim.getTotalDelays();
		finalScore = getFinalScore();
		
		score.setText(
			"<html>"
				+"<p>Delay time to beat: " + simScore + ".</p>"
				+"<p>Your current delay time: " + userScore + ".</p>"
				+"<p>Unscheduled delays are " + getFormattedScore() + "!</p>"
			+"</html>"
		);
	}
	public void showFinalScore(){
		userScore = sim.getTotalDelays();
		finalScore = getFinalScore();
		score.setText(
			"<html>"
				+"<p>The game has ended!</p>"
				+"<br>"
				+"<p>Your final delay time is " + userScore + ".</p>"
				+"<p>Your delay time to beat was " + simScore + ".</p>"
				+"<p>Unscheduled delays were " + getFormattedScore() + "!</p>"
				+"<br>"
				+"<p>Great Job!</p>"
				+"<p>Try to improve your score next time you play.</p>"
			+"</html>"
		);
		this.setVisible(true);
		
		System.out.println("The queue is now empty, and the game has ended.");
	}
}
